#include "databasemanager.h"
#include <stdexcept>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>

DatabaseManager::DatabaseManager(QObject *parent)
    : QObject(parent)
{
    // 初始化时不设置数据库路径，等待用户工作目录设置
    m_databasePath = "";
    m_userWorkDirectory = "";
}

DatabaseManager::~DatabaseManager()
{
    if (m_database.isOpen()) {
        m_database.close();
    }
}

bool DatabaseManager::initializeDatabase()
{
    // 添加SQLite驱动
    if (!QSqlDatabase::drivers().contains("QSQLITE")) {
        qDebug() << "SQLite驱动不可用";
        return false;
    }

    // 设置数据库连接
    m_database = QSqlDatabase::addDatabase("QSQLITE");
    m_database.setDatabaseName(m_databasePath);
    
    qDebug() << "SQLite数据库文件路径:" << m_databasePath;
    qDebug() << "数据库文件是否存在:" << QFile::exists(m_databasePath);

    // 打开数据库
    if (!m_database.open()) {
        qDebug() << "无法打开数据库:" << m_database.lastError().text();
        return false;
    }
    
    qDebug() << "SQLite数据库连接成功，实际使用的数据库文件:" << m_database.databaseName();
    qDebug() << "数据库文件创建后是否存在:" << QFile::exists(m_databasePath);

    // 创建表结构
    if (!createTables()) {
        qDebug() << "创建表失败";
        return false;
    }

    qDebug() << "数据库初始化成功，路径:" << m_databasePath;
    return true;
}

QString DatabaseManager::getDatabasePath()
{
    // 如果用户工作目录已设置，返回用户工作目录下的desk.db
    if (!m_userWorkDirectory.isEmpty()) {
        return QDir(m_userWorkDirectory).filePath("desk.db");
    }
    
    // 如果没有正确的用户工作目录，抛出异常
    throw std::runtime_error("用户工作目录未设置，无法确定数据库路径");
}

void DatabaseManager::setUserWorkDirectory(const QString &workDirectory)
{
    m_userWorkDirectory = workDirectory;
    qDebug() << "设置用户工作目录:" << m_userWorkDirectory;
}

bool DatabaseManager::setDatabasePath(const QString &path)
{
    qDebug() << "设置数据库路径:" << path;
    
    // 关闭当前数据库连接
    if (m_database.isOpen()) {
        qDebug() << "关闭当前数据库连接";
        m_database.close();
    }
    
    // 设置新的数据库路径
    m_databasePath = path;
    qDebug() << "新的数据库路径已设置:" << m_databasePath;
    
    // 重新初始化数据库
    return initializeDatabase();
}

bool DatabaseManager::setUserWorkDirectoryAndDatabase(const QString &workDirectory)
{
    try {
        qDebug() << "=== 开始设置用户工作目录和数据库 ===";
        qDebug() << "用户工作目录:" << workDirectory;
        qDebug() << "工作目录是否存在:" << QDir(workDirectory).exists();
        
        // 设置用户工作目录
        setUserWorkDirectory(workDirectory);
        
        // 获取正确的数据库路径
        QString databasePath = getDatabasePath();
        qDebug() << "计算得到的数据库路径:" << databasePath;
        qDebug() << "数据库文件父目录:" << QFileInfo(databasePath).absolutePath();
        qDebug() << "数据库文件父目录是否存在:" << QDir(QFileInfo(databasePath).absolutePath()).exists();
        
        // 设置数据库路径并重新初始化
        bool result = setDatabasePath(databasePath);
        qDebug() << "=== 用户工作目录和数据库设置完成，结果:" << (result ? "成功" : "失败") << " ===";
        return result;
    } catch (const std::exception &e) {
        qDebug() << "设置用户工作目录和数据库失败:" << e.what();
        return false;
    }
}

bool DatabaseManager::createTables()
{
    QSqlQuery query(m_database);
    
    // 创建网盘表
    QString createDiskTable = R"(
        CREATE TABLE IF NOT EXISTS kms_disk (
            ID TEXT NOT NULL,
            TYPE INTEGER DEFAULT NULL,
            NAME TEXT DEFAULT NULL,
            DOMAIN_ID TEXT DEFAULT NULL,
            OWNER_ID TEXT DEFAULT NULL,
            ORDER_NO INTEGER DEFAULT NULL,
            PRIMARY KEY (ID)
        )
    )";
    
    if (!query.exec(createDiskTable)) {
        qDebug() << "创建网盘表失败:" << query.lastError().text();
        return false;
    }
    qDebug() << "网盘表创建成功";
    
    // 创建文件夹表
    QString createFolderTable = R"(
        CREATE TABLE IF NOT EXISTS kms_folder (
            ID TEXT NOT NULL,
            NAME TEXT DEFAULT NULL,
            DISK_ID TEXT DEFAULT NULL,
            FOLDER_ID TEXT DEFAULT NULL,
            PATH TEXT DEFAULT NULL,
            CREATOR TEXT DEFAULT NULL,
            CREATOR_ID TEXT DEFAULT NULL,
            TYPE INTEGER DEFAULT NULL,
            CREATE_DATE TEXT DEFAULT NULL,
            LAST_MODIFY_DATE TEXT DEFAULT NULL,
            ORDER_NO INTEGER DEFAULT NULL,
            REMOVE_OPERATOR TEXT DEFAULT NULL,
            STATUS INTEGER DEFAULT 0,
            VERSION INTEGER DEFAULT 0,
            MAX_VERSION INTEGER DEFAULT 0,
            PRIMARY KEY (ID)
        )
    )";
    
    if (!query.exec(createFolderTable)) {
        qDebug() << "创建文件夹表失败:" << query.lastError().text();
        return false;
    }
    qDebug() << "文件夹表创建成功";
    
    // 创建文件表
    QString createFileTable = R"(
        CREATE TABLE IF NOT EXISTS kms_file (
            ID TEXT NOT NULL,
            NAME TEXT DEFAULT NULL,
            DISK_ID TEXT DEFAULT NULL,
            FOLDER_ID TEXT DEFAULT NULL,
            CREATOR TEXT DEFAULT NULL,
            CREATOR_ID TEXT DEFAULT NULL,
            TYPE TEXT DEFAULT NULL,
            CREATE_DATE TEXT DEFAULT NULL,
            LAST_MODIFY_DATE TEXT DEFAULT NULL,
            ORIGIN_TYPE INTEGER DEFAULT NULL,
            ORIGIN_ID TEXT DEFAULT NULL,
            SIZE INTEGER DEFAULT NULL,
            REMOVE_OPERATOR TEXT DEFAULT NULL,
            STATUS INTEGER DEFAULT 0,
            CHECKSUM TEXT DEFAULT NULL,
            LOCAL_FILE_SIZE INTEGER DEFAULT 0,
            LOCAL_FILE_CHECKSUM TEXT DEFAULT NULL,
            LOCAL_FILE_PATH TEXT DEFAULT NULL,
            PRIMARY KEY (ID)
        )
    )";
    
    if (!query.exec(createFileTable)) {
        qDebug() << "创建文件表失败:" << query.lastError().text();
        return false;
    }
    qDebug() << "文件表创建成功";
    
    // 检查并添加 LOCAL_FILE_PATH 字段（用于数据库迁移）
    QSqlQuery checkColumnQuery(m_database);
    checkColumnQuery.prepare("PRAGMA table_info(kms_file)");
    if (checkColumnQuery.exec()) {
        bool hasLocalFilePath = false;
        while (checkColumnQuery.next()) {
            if (checkColumnQuery.value("name").toString().toUpper() == "LOCAL_FILE_PATH") {
                hasLocalFilePath = true;
                break;
            }
        }
        if (!hasLocalFilePath) {
            QSqlQuery addColumnQuery(m_database);
            if (!addColumnQuery.exec("ALTER TABLE kms_file ADD COLUMN LOCAL_FILE_PATH TEXT DEFAULT NULL")) {
                qDebug() << "添加 LOCAL_FILE_PATH 字段失败:" << addColumnQuery.lastError().text();
            } else {
                qDebug() << "成功添加 LOCAL_FILE_PATH 字段";
            }
        }
    }
    
    // 创建命令表
    QString createCommandTable = R"(
        CREATE TABLE IF NOT EXISTS kms_command (
            ID TEXT NOT NULL,
            CREATE_DATE TEXT DEFAULT NULL,
            LOCAL_FILE_PATH TEXT DEFAULT NULL,
            DOWNLOAD_URL TEXT DEFAULT NULL,
            COMMIT_URL TEXT DEFAULT NULL,
            ACCESS_TOKEN TEXT DEFAULT NULL,
            COMMAND TEXT DEFAULT NULL,
            PRIMARY KEY (ID)
        )
    )";
    
    if (!query.exec(createCommandTable)) {
        qDebug() << "创建命令表失败:" << query.lastError().text();
        return false;
    }
    qDebug() << "命令表创建成功";
    
    // 检查并添加 ACCESS_TOKEN 字段（用于数据库迁移）
    QSqlQuery checkCommandColumnQuery(m_database);
    checkCommandColumnQuery.prepare("PRAGMA table_info(kms_command)");
    if (checkCommandColumnQuery.exec()) {
        bool hasAccessToken = false;
        bool hasCommand = false;
        while (checkCommandColumnQuery.next()) {
            QString columnName = checkCommandColumnQuery.value("name").toString().toUpper();
            if (columnName == "ACCESS_TOKEN") {
                hasAccessToken = true;
            } else if (columnName == "COMMAND") {
                hasCommand = true;
            }
        }
        if (!hasAccessToken) {
            QSqlQuery addColumnQuery(m_database);
            if (!addColumnQuery.exec("ALTER TABLE kms_command ADD COLUMN ACCESS_TOKEN TEXT DEFAULT NULL")) {
                qDebug() << "添加 ACCESS_TOKEN 字段失败:" << addColumnQuery.lastError().text();
            } else {
                qDebug() << "成功添加 ACCESS_TOKEN 字段";
            }
        }
        if (!hasCommand) {
            QSqlQuery addColumnQuery(m_database);
            if (!addColumnQuery.exec("ALTER TABLE kms_command ADD COLUMN COMMAND TEXT DEFAULT NULL")) {
                qDebug() << "添加 COMMAND 字段失败:" << addColumnQuery.lastError().text();
            } else {
                qDebug() << "成功添加 COMMAND 字段";
            }
        }
    }
    
    qDebug() << "所有数据表创建完成";
    return true;
}

bool DatabaseManager::isDatabaseConnected()
{
    return m_database.isOpen() && m_database.isValid();
}

// 网盘记录操作
bool DatabaseManager::insertDisk(const KmsDisk &disk)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("INSERT INTO kms_disk (ID, TYPE, NAME, DOMAIN_ID, OWNER_ID, ORDER_NO) "
                  "VALUES (?, ?, ?, ?, ?, ?)");
    
    query.addBindValue(disk.id);
    query.addBindValue(disk.type);
    query.addBindValue(disk.name);
    query.addBindValue(disk.domainId);
    query.addBindValue(disk.ownerId);
    query.addBindValue(disk.orderNo);
    
    if (!query.exec()) {
        qDebug() << "插入网盘记录失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}

bool DatabaseManager::updateDisk(const KmsDisk &disk)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("UPDATE kms_disk SET TYPE=?, NAME=?, DOMAIN_ID=?, OWNER_ID=?, ORDER_NO=? "
                  "WHERE ID=?");
    
    query.addBindValue(disk.type);
    query.addBindValue(disk.name);
    query.addBindValue(disk.domainId);
    query.addBindValue(disk.ownerId);
    query.addBindValue(disk.orderNo);
    query.addBindValue(disk.id);
    
    if (!query.exec()) {
        qDebug() << "更新网盘记录失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}

QList<KmsDisk> DatabaseManager::queryDisksByName(const QString &name)
{
    QList<KmsDisk> disks;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return disks;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_disk WHERE NAME LIKE ?");
    query.addBindValue("%" + name + "%");
    
    if (!query.exec()) {
        qDebug() << "查询网盘记录失败:" << query.lastError().text();
        return disks;
    }
    
    while (query.next()) {
        KmsDisk disk;
        disk.id = query.value("ID").toString();
        disk.type = query.value("TYPE").toInt();
        disk.name = query.value("NAME").toString();
        disk.domainId = query.value("DOMAIN_ID").toString();
        disk.ownerId = query.value("OWNER_ID").toString();
        disk.orderNo = query.value("ORDER_NO").toInt();
        disks.append(disk);
    }
    
    return disks;
}

QList<KmsDisk> DatabaseManager::queryAllDisks()
{
    QList<KmsDisk> disks;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return disks;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_disk");
    
    if (!query.exec()) {
        qDebug() << "查询所有网盘记录失败:" << query.lastError().text();
        return disks;
    }
    
    while (query.next()) {
        KmsDisk disk;
        disk.id = query.value("ID").toString();
        disk.type = query.value("TYPE").toInt();
        disk.name = query.value("NAME").toString();
        disk.domainId = query.value("DOMAIN_ID").toString();
        disk.ownerId = query.value("OWNER_ID").toString();
        disk.orderNo = query.value("ORDER_NO").toInt();
        disks.append(disk);
    }
    
    return disks;
}

// 文件夹记录操作
bool DatabaseManager::insertFolder(const KmsFolder &folder)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("INSERT INTO kms_folder (ID, NAME, DISK_ID, FOLDER_ID, PATH, CREATOR, "
                  "CREATOR_ID, TYPE, CREATE_DATE, LAST_MODIFY_DATE, ORDER_NO, REMOVE_OPERATOR, "
                  "STATUS, VERSION, MAX_VERSION) "
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    query.addBindValue(folder.id);
    query.addBindValue(folder.name);
    query.addBindValue(folder.diskId);
    query.addBindValue(folder.folderId);
    query.addBindValue(folder.path);
    query.addBindValue(folder.creator);
    query.addBindValue(folder.creatorId);
    query.addBindValue(folder.type);
    query.addBindValue(folder.createDate);
    query.addBindValue(folder.lastModifyDate);
    query.addBindValue(folder.orderNo);
    query.addBindValue(folder.removeOperator);
    query.addBindValue(folder.status);
    query.addBindValue(folder.version);
    query.addBindValue(folder.maxVersion);
    
    if (!query.exec()) {
        qDebug() << "插入文件夹记录失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}

bool DatabaseManager::updateFolder(const KmsFolder &folder)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("UPDATE kms_folder SET NAME=?, DISK_ID=?, FOLDER_ID=?, PATH=?, CREATOR=?, "
                  "CREATOR_ID=?, TYPE=?, CREATE_DATE=?, LAST_MODIFY_DATE=?, ORDER_NO=?, REMOVE_OPERATOR=?, "
                  "STATUS=?, VERSION=?, MAX_VERSION=? "
                  "WHERE ID=?");
    
    query.addBindValue(folder.name);
    query.addBindValue(folder.diskId);
    query.addBindValue(folder.folderId);
    query.addBindValue(folder.path);
    query.addBindValue(folder.creator);
    query.addBindValue(folder.creatorId);
    query.addBindValue(folder.type);
    query.addBindValue(folder.createDate);
    query.addBindValue(folder.lastModifyDate);
    query.addBindValue(folder.orderNo);
    query.addBindValue(folder.removeOperator);
    query.addBindValue(folder.status);
    query.addBindValue(folder.version);
    query.addBindValue(folder.maxVersion);
    query.addBindValue(folder.id);
    
    if (!query.exec()) {
        qDebug() << "更新文件夹记录失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}

QList<KmsFolder> DatabaseManager::queryFoldersByPath(const QString &path)
{
    QList<KmsFolder> folders;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return folders;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_folder WHERE PATH LIKE ?");
    query.addBindValue("%" + path + "%");
    
    if (!query.exec()) {
        qDebug() << "查询文件夹记录失败:" << query.lastError().text();
        return folders;
    }
    
    while (query.next()) {
        KmsFolder folder;
        folder.id = query.value("ID").toString();
        folder.name = query.value("NAME").toString();
        folder.diskId = query.value("DISK_ID").toString();
        folder.folderId = query.value("FOLDER_ID").toString();
        folder.path = query.value("PATH").toString();
        folder.creator = query.value("CREATOR").toString();
        folder.creatorId = query.value("CREATOR_ID").toString();
        folder.type = query.value("TYPE").toInt();
        folder.createDate = query.value("CREATE_DATE").toString();
        folder.lastModifyDate = query.value("LAST_MODIFY_DATE").toString();
        folder.orderNo = query.value("ORDER_NO").toInt();
        folder.removeOperator = query.value("REMOVE_OPERATOR").toString();
        folder.status = query.value("STATUS").toInt();
        folder.version = query.value("VERSION").toInt();
        folder.maxVersion = query.value("MAX_VERSION").toInt();
        folders.append(folder);
    }
    
    return folders;
}

KmsFolder DatabaseManager::queryFolderByExactPath(const QString &path)
{
    KmsFolder folder;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return folder;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_folder WHERE PATH = ?");
    query.addBindValue(path);
    
    if (!query.exec()) {
        qDebug() << "精确查询文件夹记录失败:" << query.lastError().text();
        return folder;
    }
    
    if (query.next()) {
        folder.id = query.value("ID").toString();
        folder.name = query.value("NAME").toString();
        folder.diskId = query.value("DISK_ID").toString();
        folder.folderId = query.value("FOLDER_ID").toString();
        folder.path = query.value("PATH").toString();
        folder.creator = query.value("CREATOR").toString();
        folder.creatorId = query.value("CREATOR_ID").toString();
        folder.type = query.value("TYPE").toInt();
        folder.createDate = query.value("CREATE_DATE").toString();
        folder.lastModifyDate = query.value("LAST_MODIFY_DATE").toString();
        folder.orderNo = query.value("ORDER_NO").toInt();
        folder.removeOperator = query.value("REMOVE_OPERATOR").toString();
        folder.status = query.value("STATUS").toInt();
        folder.version = query.value("VERSION").toInt();
        folder.maxVersion = query.value("MAX_VERSION").toInt();
    }
    
    return folder;
}

KmsFolder DatabaseManager::queryFolderById(const QString &folderId)
{
    KmsFolder folder;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return folder;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_folder WHERE ID = ?");
    query.addBindValue(folderId);
    
    if (!query.exec()) {
        qDebug() << "根据ID查询文件夹记录失败:" << query.lastError().text();
        return folder;
    }
    
    if (query.next()) {
        folder.id = query.value("ID").toString();
        folder.name = query.value("NAME").toString();
        folder.diskId = query.value("DISK_ID").toString();
        folder.folderId = query.value("FOLDER_ID").toString();
        folder.path = query.value("PATH").toString();
        folder.creator = query.value("CREATOR").toString();
        folder.creatorId = query.value("CREATOR_ID").toString();
        folder.type = query.value("TYPE").toInt();
        folder.createDate = query.value("CREATE_DATE").toString();
        folder.lastModifyDate = query.value("LAST_MODIFY_DATE").toString();
        folder.orderNo = query.value("ORDER_NO").toInt();
        folder.removeOperator = query.value("REMOVE_OPERATOR").toString();
        folder.status = query.value("STATUS").toInt();
        folder.version = query.value("VERSION").toInt();
        folder.maxVersion = query.value("MAX_VERSION").toInt();
    }
    
    return folder;
}

QList<KmsFolder> DatabaseManager::queryAllFolders()
{
    QList<KmsFolder> folders;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return folders;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_folder");
    
    if (!query.exec()) {
        qDebug() << "查询所有文件夹记录失败:" << query.lastError().text();
        return folders;
    }
    
    while (query.next()) {
        KmsFolder folder;
        folder.id = query.value("ID").toString();
        folder.name = query.value("NAME").toString();
        folder.diskId = query.value("DISK_ID").toString();
        folder.folderId = query.value("FOLDER_ID").toString();
        folder.path = query.value("PATH").toString();
        folder.creator = query.value("CREATOR").toString();
        folder.creatorId = query.value("CREATOR_ID").toString();
        folder.type = query.value("TYPE").toInt();
        folder.createDate = query.value("CREATE_DATE").toString();
        folder.lastModifyDate = query.value("LAST_MODIFY_DATE").toString();
        folder.orderNo = query.value("ORDER_NO").toInt();
        folder.removeOperator = query.value("REMOVE_OPERATOR").toString();
        folder.status = query.value("STATUS").toInt();
        folder.version = query.value("VERSION").toInt();
        folder.maxVersion = query.value("MAX_VERSION").toInt();
        folders.append(folder);
    }
    
    return folders;
}

// 文件记录操作
bool DatabaseManager::insertFile(const KmsFile &file)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("INSERT INTO kms_file (ID, NAME, DISK_ID, FOLDER_ID, CREATOR, CREATOR_ID, "
                  "TYPE, CREATE_DATE, LAST_MODIFY_DATE, ORIGIN_TYPE, ORIGIN_ID, SIZE, "
                  "REMOVE_OPERATOR, STATUS, CHECKSUM, LOCAL_FILE_SIZE, LOCAL_FILE_CHECKSUM, LOCAL_FILE_PATH) "
                  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    query.addBindValue(file.id);
    query.addBindValue(file.name);
    query.addBindValue(file.diskId);
    query.addBindValue(file.folderId);
    query.addBindValue(file.creator);
    query.addBindValue(file.creatorId);
    query.addBindValue(file.type);
    query.addBindValue(file.createDate);
    query.addBindValue(file.lastModifyDate);
    query.addBindValue(file.originType);
    query.addBindValue(file.originId);
    query.addBindValue(file.size);
    query.addBindValue(file.removeOperator);
    query.addBindValue(file.status);
    query.addBindValue(file.checksum);
    query.addBindValue(file.localFileSize);
    query.addBindValue(file.localFileChecksum);
    query.addBindValue(file.localFilePath);
    
    if (!query.exec()) {
        qDebug() << "插入文件记录失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}

bool DatabaseManager::updateFile(const KmsFile &file)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("UPDATE kms_file SET NAME=?, DISK_ID=?, FOLDER_ID=?, CREATOR=?, CREATOR_ID=?, "
                  "TYPE=?, CREATE_DATE=?, LAST_MODIFY_DATE=?, ORIGIN_TYPE=?, ORIGIN_ID=?, SIZE=?, "
                  "REMOVE_OPERATOR=?, STATUS=?, CHECKSUM=?, LOCAL_FILE_SIZE=?, LOCAL_FILE_CHECKSUM=?, LOCAL_FILE_PATH=? WHERE ID=?");
    
    query.addBindValue(file.name);
    query.addBindValue(file.diskId);
    query.addBindValue(file.folderId);
    query.addBindValue(file.creator);
    query.addBindValue(file.creatorId);
    query.addBindValue(file.type);
    query.addBindValue(file.createDate);
    query.addBindValue(file.lastModifyDate);
    query.addBindValue(file.originType);
    query.addBindValue(file.originId);
    query.addBindValue(file.size);
    query.addBindValue(file.removeOperator);
    query.addBindValue(file.status);
    query.addBindValue(file.checksum);
    query.addBindValue(file.localFileSize);
    query.addBindValue(file.localFileChecksum);
    query.addBindValue(file.localFilePath);
    query.addBindValue(file.id);
    
    if (!query.exec()) {
        qDebug() << "更新文件记录失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}

QList<KmsFile> DatabaseManager::queryFilesByPath(const QString &path)
{
    QList<KmsFile> files;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return files;
    }
    
    // 注意：PATH字段已移除，此方法已废弃，返回空列表
    qDebug() << "警告：queryFilesByPath方法已废弃（PATH字段已移除）";
    return files;
}

QList<KmsFile> DatabaseManager::queryFilesByFolderId(const QString &folderId)
{
    QList<KmsFile> files;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return files;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_file WHERE FOLDER_ID = ?");
    query.addBindValue(folderId);
    
    if (!query.exec()) {
        qDebug() << "查询文件失败:" << query.lastError().text();
        return files;
    }
    
    while (query.next()) {
        KmsFile file;
        file.id = query.value("ID").toString();
        file.name = query.value("NAME").toString();
        file.diskId = query.value("DISK_ID").toString();
        file.folderId = query.value("FOLDER_ID").toString();
        file.creator = query.value("CREATOR").toString();
        file.creatorId = query.value("CREATOR_ID").toString();
        file.type = query.value("TYPE").toString();
        file.createDate = query.value("CREATE_DATE").toString();
        file.lastModifyDate = query.value("LAST_MODIFY_DATE").toString();
        file.originType = query.value("ORIGIN_TYPE").toInt();
        file.originId = query.value("ORIGIN_ID").toString();
        file.size = query.value("SIZE").toLongLong();
        file.removeOperator = query.value("REMOVE_OPERATOR").toString();
        file.status = query.value("STATUS").toInt();
        file.checksum = query.value("CHECKSUM").toString();
        file.localFileSize = query.value("LOCAL_FILE_SIZE").toLongLong();
        file.localFileChecksum = query.value("LOCAL_FILE_CHECKSUM").toString();
        file.localFilePath = query.value("LOCAL_FILE_PATH").toString();
        files.append(file);
    }
    
    return files;
}

QList<KmsFile> DatabaseManager::queryAllFiles()
{
    QList<KmsFile> files;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return files;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_file");
    
    if (!query.exec()) {
        qDebug() << "查询所有文件记录失败:" << query.lastError().text();
        return files;
    }
    
    while (query.next()) {
        KmsFile file;
        file.id = query.value("ID").toString();
        file.name = query.value("NAME").toString();
        file.diskId = query.value("DISK_ID").toString();
        file.folderId = query.value("FOLDER_ID").toString();
        file.creator = query.value("CREATOR").toString();
        file.creatorId = query.value("CREATOR_ID").toString();
        file.type = query.value("TYPE").toString();
        file.createDate = query.value("CREATE_DATE").toString();
        file.lastModifyDate = query.value("LAST_MODIFY_DATE").toString();
        file.originType = query.value("ORIGIN_TYPE").toInt();
        file.originId = query.value("ORIGIN_ID").toString();
        file.size = query.value("SIZE").toLongLong();
        file.removeOperator = query.value("REMOVE_OPERATOR").toString();
        file.status = query.value("STATUS").toInt();
        file.checksum = query.value("CHECKSUM").toString();
        file.localFileSize = query.value("LOCAL_FILE_SIZE").toLongLong();
        file.localFileChecksum = query.value("LOCAL_FILE_CHECKSUM").toString();
        file.localFilePath = query.value("LOCAL_FILE_PATH").toString();
        files.append(file);
    }
    
    return files;
}

KmsFile DatabaseManager::queryFileById(const QString &fileId)
{
    KmsFile file;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return file;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_file WHERE ID = ?");
    query.addBindValue(fileId);
    
    if (!query.exec()) {
        qDebug() << "根据ID查询文件记录失败:" << query.lastError().text();
        return file;
    }
    
    if (query.next()) {
        file.id = query.value("ID").toString();
        file.name = query.value("NAME").toString();
        file.diskId = query.value("DISK_ID").toString();
        file.folderId = query.value("FOLDER_ID").toString();
        file.originType = query.value("ORIGIN_TYPE").toInt();
        file.originId = query.value("ORIGIN_ID").toString();
        file.size = query.value("SIZE").toLongLong();
        file.removeOperator = query.value("REMOVE_OPERATOR").toString();
        file.status = query.value("STATUS").toInt();
        file.checksum = query.value("CHECKSUM").toString();
        file.localFileSize = query.value("LOCAL_FILE_SIZE").toLongLong();
        file.localFileChecksum = query.value("LOCAL_FILE_CHECKSUM").toString();
        file.localFilePath = query.value("LOCAL_FILE_PATH").toString();
    }
    
    return file;
}

bool DatabaseManager::updateFileFromJson(const QJsonObject &fileData)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    QString fileId = fileData["id"].toString();
    if (fileId.isEmpty()) {
        qDebug() << "文件ID为空，无法更新";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("UPDATE kms_file SET "
                  "NAME = ?, DISK_ID = ?, FOLDER_ID = ?, ORIGIN_TYPE = ?, ORIGIN_ID = ?, "
                  "SIZE = ?, REMOVE_OPERATOR = ?, STATUS = ?, CHECKSUM = ? "
                  "WHERE ID = ?");
    
    query.addBindValue(fileData["name"].toString());
    query.addBindValue(fileData["diskId"].toString());
    query.addBindValue(fileData["folderId"].toString());
    query.addBindValue(fileData["originType"].toInt());
    query.addBindValue(fileData["originId"].toString());
    query.addBindValue(fileData["size"].toVariant());
    query.addBindValue(fileData["removeOperator"].toString());
    query.addBindValue(fileData["delete"].toBool() ? 0 : 1); // 如果delete为true，状态为0，否则为1
    query.addBindValue(fileData["checksum"].toString());
    query.addBindValue(fileId);
    
    if (!query.exec()) {
        qDebug() << "更新文件信息失败:" << query.lastError().text();
        return false;
    }
    
    qDebug() << "成功更新文件信息，文件ID:" << fileId;
    return true;
}

void DatabaseManager::insertTestFolderData()
{
    qDebug() << "=== 开始插入测试文件夹数据 ===";
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接，无法插入测试数据";
        return;
    }
    
    // 插入测试文件夹数据
    KmsFolder folder1;
    folder1.id = "folder001";
    folder1.name = "测试文件夹1";
    folder1.diskId = "disk001";
    folder1.folderId = ""; // 顶级文件夹
    folder1.path = "/测试文件夹1";
    folder1.creator = "admin";
    folder1.creatorId = "admin001";
    folder1.type = 1;
    folder1.createDate = "2024-01-01 10:00:00";
    folder1.lastModifyDate = "2024-01-01 10:00:00";
    folder1.orderNo = 1;
    folder1.removeOperator = "";
    folder1.status = 0; // 未同步
    folder1.version = 1;
    folder1.maxVersion = 1;
    
    if (insertFolder(folder1)) {
        qDebug() << "成功插入测试文件夹1";
    } else {
        qDebug() << "插入测试文件夹1失败";
    }
    
    KmsFolder folder2;
    folder2.id = "folder002";
    folder2.name = "测试文件夹2";
    folder2.diskId = "disk001";
    folder2.folderId = ""; // 顶级文件夹
    folder2.path = "/测试文件夹2";
    folder2.creator = "admin";
    folder2.creatorId = "admin001";
    folder2.type = 1;
    folder2.createDate = "2024-01-01 10:00:00";
    folder2.lastModifyDate = "2024-01-01 10:00:00";
    folder2.orderNo = 2;
    folder2.removeOperator = "";
    folder2.status = 1; // 已同步
    folder2.version = 1;
    folder2.maxVersion = 1;
    
    if (insertFolder(folder2)) {
        qDebug() << "成功插入测试文件夹2";
    } else {
        qDebug() << "插入测试文件夹2失败";
    }
    
    KmsFolder folder3;
    folder3.id = "folder003";
    folder3.name = "测试文件夹3";
    folder3.diskId = "disk001";
    folder3.folderId = ""; // 顶级文件夹
    folder3.path = "/测试文件夹3";
    folder3.creator = "admin";
    folder3.creatorId = "admin001";
    folder3.type = 1;
    folder3.createDate = "2024-01-01 10:00:00";
    folder3.lastModifyDate = "2024-01-01 10:00:00";
    folder3.orderNo = 3;
    folder3.removeOperator = "";
    folder3.status = -1; // 已删除
    folder3.version = 1;
    folder3.maxVersion = 1;
    
    if (insertFolder(folder3)) {
        qDebug() << "成功插入测试文件夹3";
    } else {
        qDebug() << "插入测试文件夹3失败";
    }
    
    qDebug() << "=== 测试文件夹数据插入完成 ===";
}

bool DatabaseManager::syncDisksFromJson(const QJsonArray &disksData)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接，无法同步网盘数据";
        return false;
    }
    
    qDebug() << "开始同步网盘数据，数量:" << disksData.size();
    
    // 开始事务
    m_database.transaction();
    
    try {
        // 准备 INSERT 和 UPDATE 查询
        QSqlQuery insertQuery(m_database);
        insertQuery.prepare("INSERT INTO kms_disk (ID, TYPE, NAME, DOMAIN_ID, OWNER_ID, ORDER_NO) VALUES (?, ?, ?, ?, ?, ?)");
        
        QSqlQuery updateQuery(m_database);
        updateQuery.prepare("UPDATE kms_disk SET TYPE=?, NAME=?, DOMAIN_ID=?, OWNER_ID=?, ORDER_NO=? WHERE ID=?");
        
        // 获取当前数据库中存在的网盘ID列表
        QSet<QString> existingDiskIds;
        QSqlQuery selectQuery(m_database);
        if (selectQuery.exec("SELECT ID FROM kms_disk")) {
            while (selectQuery.next()) {
                existingDiskIds.insert(selectQuery.value(0).toString());
            }
        }
        
        QSet<QString> newDiskIds;
        int insertCount = 0;
        int updateCount = 0;
        
        for (int i = 0; i < disksData.size(); ++i) {
            QJsonValue value = disksData[i];
            if (value.isObject()) {
                QJsonObject diskObj = value.toObject();
                
                KmsDisk disk;
                disk.id = diskObj["id"].toString();
                disk.type = diskObj["type"].toInt();
                disk.name = diskObj["name"].toString();
                disk.domainId = diskObj["domainId"].toString();
                disk.ownerId = diskObj["ownerId"].toString();
                disk.orderNo = diskObj["orderNo"].toInt();
                
                newDiskIds.insert(disk.id);
                
                qDebug() << "同步网盘 - ID:" << disk.id << "名称:" << disk.name << "类型:" << disk.type;
                
                if (existingDiskIds.contains(disk.id)) {
                    // 更新现有记录
                    updateQuery.addBindValue(disk.type);
                    updateQuery.addBindValue(disk.name);
                    updateQuery.addBindValue(disk.domainId);
                    updateQuery.addBindValue(disk.ownerId);
                    updateQuery.addBindValue(disk.orderNo);
                    updateQuery.addBindValue(disk.id);
                    
                    if (updateQuery.exec()) {
                        updateCount++;
                        qDebug() << "成功更新网盘:" << disk.name;
                    } else {
                        qDebug() << "更新网盘失败:" << disk.name << "错误:" << updateQuery.lastError().text();
                    }
                } else {
                    // 插入新记录
                    insertQuery.addBindValue(disk.id);
                    insertQuery.addBindValue(disk.type);
                    insertQuery.addBindValue(disk.name);
                    insertQuery.addBindValue(disk.domainId);
                    insertQuery.addBindValue(disk.ownerId);
                    insertQuery.addBindValue(disk.orderNo);
                    
                    if (insertQuery.exec()) {
                        insertCount++;
                        qDebug() << "成功插入网盘:" << disk.name;
                    } else {
                        qDebug() << "插入网盘失败:" << disk.name << "错误:" << insertQuery.lastError().text();
                    }
                }
            }
        }
        
        // 逻辑删除：将服务器上不存在的网盘标记为删除状态
        // 注意：这里假设网盘表有 STATUS 字段来标记删除状态
        // 如果没有 STATUS 字段，可以跳过这一步或者添加该字段
        QSqlQuery deleteQuery(m_database);
        deleteQuery.prepare("UPDATE kms_disk SET STATUS = -1 WHERE ID = ?");
        
        int deleteCount = 0;
        for (const QString &diskId : existingDiskIds) {
            if (!newDiskIds.contains(diskId)) {
                deleteQuery.addBindValue(diskId);
                if (deleteQuery.exec()) {
                    deleteCount++;
                    qDebug() << "逻辑删除网盘:" << diskId;
                }
            }
        }
        
        // 提交事务
        if (m_database.commit()) {
            qDebug() << "网盘数据同步完成 - 插入:" << insertCount << "更新:" << updateCount << "删除:" << deleteCount;
            return true;
        } else {
            qDebug() << "提交事务失败:" << m_database.lastError().text();
            m_database.rollback();
            return false;
        }
        
    } catch (...) {
        qDebug() << "同步网盘数据时发生异常";
        m_database.rollback();
        return false;
    }
}

bool DatabaseManager::syncFoldersFromJson(const QJsonArray &foldersData)
{
    if (!m_database.isOpen()) {
        qDebug() << "数据库未打开，无法同步文件夹数据";
        return false;
    }
    
    try {
        m_database.transaction();
        
        // 准备 INSERT 和 UPDATE 查询
        QSqlQuery insertQuery(m_database);
        insertQuery.prepare("INSERT INTO kms_folder (ID, NAME, CREATOR_ID, CREATOR, CREATE_DATE, LAST_MODIFY_DATE, DISK_ID, FOLDER_ID, PATH, TYPE, ORDER_NO, REMOVE_OPERATOR, VERSION, MAX_VERSION) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        QSqlQuery updateQuery(m_database);
        updateQuery.prepare("UPDATE kms_folder SET NAME=?, CREATOR_ID=?, CREATOR=?, CREATE_DATE=?, LAST_MODIFY_DATE=?, DISK_ID=?, FOLDER_ID=?, PATH=?, TYPE=?, ORDER_NO=?, REMOVE_OPERATOR=?, VERSION=?, MAX_VERSION=? WHERE ID=?");
        
        // 第一步：收集服务器返回的网盘ID
        QSet<QString> syncDiskIds;  // 本次同步涉及的网盘ID集合
        for (const QJsonValue &value : foldersData) {
            if (!value.isObject()) {
                continue;
            }
            QJsonObject folderObj = value.toObject();
            QString diskId = folderObj["diskId"].toString();
            if (!diskId.isEmpty()) {
                syncDiskIds.insert(diskId);
            }
        }
        
        // 第二步：根据网盘ID查询数据库中已存在的文件夹ID
        QSet<QString> existingFolderIds;
        if (!syncDiskIds.isEmpty()) {
            QSqlQuery selectQuery(m_database);
            QString diskIdPlaceholders;
            for (int i = 0; i < syncDiskIds.size(); ++i) {
                if (i > 0) diskIdPlaceholders += ",";
                diskIdPlaceholders += "?";
            }
            QString selectSql = QString("SELECT ID FROM kms_folder WHERE DISK_ID IN (%1)").arg(diskIdPlaceholders);
            selectQuery.prepare(selectSql);
            for (const QString &diskId : syncDiskIds) {
                selectQuery.addBindValue(diskId);
            }
            if (selectQuery.exec()) {
                while (selectQuery.next()) {
                    existingFolderIds.insert(selectQuery.value(0).toString());
                }
            }
        }
        
        // 第三步：遍历服务器数据，进行插入或更新
        QSet<QString> newFolderIds;
        int insertCount = 0;
        int updateCount = 0;
        
        for (const QJsonValue &value : foldersData) {
            if (!value.isObject()) {
                qDebug() << "跳过非对象类型的文件夹数据";
                continue;
            }
            
            QJsonObject folderObj = value.toObject();
            
            // 提取文件夹数据
            QString id = folderObj["id"].toString();
            
            // 如果ID为空，跳过此记录
            if (id.isEmpty()) {
                qDebug() << "跳过ID为空的文件夹数据";
                continue;
            }
            
            QString name = folderObj["name"].toString();
            QString creatorId = folderObj["creatorId"].toString();
            QString creator = folderObj["creator"].toString();
            QString createDate = folderObj["createDate"].toString();
            QString lastModifyDate = folderObj["lastModifyDate"].toString();
            QString diskId = folderObj["diskId"].toString();
            QString folderId = folderObj["folderId"].toString();
            bool folder = folderObj["folder"].toBool();
            qint64 size = folderObj["size"].toVariant().toLongLong();
            QString path = folderObj["path"].toString();
            QString removeOperator = folderObj["removeOperator"].toString();
            int orderNo = folderObj["orderNo"].toInt();
            int type = folderObj["type"].toInt();
            int version = folderObj["version"].toInt(0);     // 从接口获取version，默认为0
            int maxVersion = folderObj["maxVersion"].toInt(0); // 从接口获取maxVersion，默认为0
            
            // 收集文件夹ID
            newFolderIds.insert(id);
            
            if (existingFolderIds.contains(id)) {
                // 更新现有记录
                updateQuery.bindValue(0, name);                  // NAME
                updateQuery.bindValue(1, creatorId);             // CREATOR_ID
                updateQuery.bindValue(2, creator);               // CREATOR
                updateQuery.bindValue(3, createDate);            // CREATE_DATE
                updateQuery.bindValue(4, lastModifyDate);        // LAST_MODIFY_DATE
                updateQuery.bindValue(5, diskId);                // DISK_ID
                updateQuery.bindValue(6, folderId);              // FOLDER_ID
                updateQuery.bindValue(7, path);                  // PATH
                updateQuery.bindValue(8, type);                  // TYPE
                updateQuery.bindValue(9, orderNo);               // ORDER_NO
                updateQuery.bindValue(10, removeOperator);       // REMOVE_OPERATOR
                // 注意：不更新STATUS字段，让文件夹状态由文件状态变更驱动
                updateQuery.bindValue(11, version);              // VERSION
                updateQuery.bindValue(12, maxVersion);           // MAX_VERSION
                updateQuery.bindValue(13, id);                   // WHERE ID
                
                if (updateQuery.exec()) {
                    updateCount++;
                    qDebug() << "成功更新文件夹:" << name;
                } else {
                    qDebug() << "更新文件夹失败:" << name << "错误:" << updateQuery.lastError().text();
                }
            } else {
                // 插入新记录
                insertQuery.bindValue(0, id);                    // ID
                insertQuery.bindValue(1, name);                  // NAME
                insertQuery.bindValue(2, creatorId);             // CREATOR_ID
                insertQuery.bindValue(3, creator);               // CREATOR
                insertQuery.bindValue(4, createDate);            // CREATE_DATE
                insertQuery.bindValue(5, lastModifyDate);        // LAST_MODIFY_DATE
                insertQuery.bindValue(6, diskId);                // DISK_ID
                insertQuery.bindValue(7, folderId);              // FOLDER_ID
                insertQuery.bindValue(8, path);                  // PATH
                insertQuery.bindValue(9, type);                  // TYPE
                insertQuery.bindValue(10, orderNo);              // ORDER_NO
                insertQuery.bindValue(11, removeOperator);       // REMOVE_OPERATOR
                // 注意：不设置STATUS字段，使用数据库默认值，让文件夹状态由文件状态变更驱动
                insertQuery.bindValue(12, version);              // VERSION
                insertQuery.bindValue(13, maxVersion);           // MAX_VERSION
                
                if (insertQuery.exec()) {
                    insertCount++;
                    qDebug() << "成功插入文件夹:" << name;
                } else {
                    qDebug() << "插入文件夹失败:" << name << "错误:" << insertQuery.lastError().text();
                }
            }
        }
        
        // 逻辑删除：将服务器上不存在的文件夹标记为删除状态
        // 重要：只对本次同步涉及的网盘下的文件夹进行逻辑删除，避免误删其他网盘的文件夹
        // 注意：只标记当前状态不是-1的文件夹，避免重复标记已删除的文件夹
        int deleteCount = 0;
        
        if (!syncDiskIds.isEmpty() && !existingFolderIds.isEmpty()) {
            qDebug() << "同步文件夹 - 本次同步的网盘ID数量:" << syncDiskIds.size() 
                     << "网盘下已有文件夹数量:" << existingFolderIds.size()
                     << "服务器返回的文件夹数量:" << newFolderIds.size();
            
            // 只对本次同步网盘下的文件夹进行逻辑删除检查
            for (const QString &folderId : existingFolderIds) {
                if (!folderId.isEmpty() && !newFolderIds.contains(folderId)) {
                    QSqlQuery deleteQuery(m_database);
                    deleteQuery.prepare("UPDATE kms_folder SET STATUS = -1 WHERE ID = ? AND STATUS != -1");
                    deleteQuery.addBindValue(folderId);
                    if (deleteQuery.exec() && deleteQuery.numRowsAffected() > 0) {
                        deleteCount++;
                        qDebug() << "逻辑删除文件夹:" << folderId;
                    }
                }
            }
        } else {
            if (syncDiskIds.isEmpty()) {
                qDebug() << "同步文件夹 - 警告：没有检测到网盘ID，跳过逻辑删除步骤";
            } else {
                qDebug() << "同步文件夹 - 本次同步网盘下没有已存在的文件夹，无需逻辑删除";
            }
        }
        
        m_database.commit();
        qDebug() << "同步文件夹数据完成 - 插入:" << insertCount << "更新:" << updateCount << "删除:" << deleteCount;
        return true;
        
    } catch (const std::exception &e) {
        qDebug() << "同步文件夹数据时发生异常:" << e.what();
        m_database.rollback();
        return false;
    } catch (...) {
        qDebug() << "同步文件夹数据时发生异常";
        m_database.rollback();
        return false;
    }
}

bool DatabaseManager::syncFilesFromJson(const QJsonArray &filesData)
{
    if (!m_database.isOpen()) {
        qDebug() << "数据库未打开，无法同步文件数据";
        return false;
    }
    
    try {
        m_database.transaction();
        
        // 准备 INSERT 和 UPDATE 查询（不更新本地字段 LOCAL_FILE_SIZE/LOCAL_FILE_CHECKSUM）
        QSqlQuery insertQuery(m_database);
        insertQuery.prepare("INSERT INTO kms_file (ID, NAME, DISK_ID, FOLDER_ID, CREATOR, CREATOR_ID, TYPE, CREATE_DATE, LAST_MODIFY_DATE, ORIGIN_TYPE, ORIGIN_ID, SIZE, REMOVE_OPERATOR, CHECKSUM) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n");
        
        QSqlQuery updateQuery(m_database);
        updateQuery.prepare("UPDATE kms_file SET NAME=?, DISK_ID=?, FOLDER_ID=?, CREATOR=?, CREATOR_ID=?, TYPE=?, CREATE_DATE=?, LAST_MODIFY_DATE=?, ORIGIN_TYPE=?, ORIGIN_ID=?, SIZE=?, REMOVE_OPERATOR=?, CHECKSUM=? WHERE ID=?");
        
        // 获取当前数据库中存在的文件ID列表
        QSet<QString> existingFileIds;
        QSqlQuery selectQuery(m_database);
        if (selectQuery.exec("SELECT ID FROM kms_file")) {
            while (selectQuery.next()) {
                existingFileIds.insert(selectQuery.value(0).toString());
            }
        }
        
        QSet<QString> newFileIds;
        int insertCount = 0;
        int updateCount = 0;
        
        for (const QJsonValue &value : filesData) {
            if (!value.isObject()) {
                qDebug() << "跳过非对象类型的文件数据";
                continue;
            }
            
            QJsonObject fileObj = value.toObject();
            
            // 提取文件数据（精简字段）
            QString id = fileObj["id"].toString();
            QString name = fileObj["name"].toString();
            QString diskId = fileObj["diskId"].toString();
            QString folderId = fileObj["folderId"].toString();
            QString creator = fileObj["creator"].toString();
            QString creatorId = fileObj["creatorId"].toString();
            QString type = fileObj["type"].toString();
            QString createDate = fileObj["createDate"].toString();
            QString lastModifyDate = fileObj["lastModifyDate"].toString();
            int originType = fileObj["originType"].toInt();
            QString originId = fileObj["originId"].toString();
            qint64 size = fileObj["size"].toVariant().toLongLong();
            QString removeOperator = fileObj["removeOperator"].toString();
            QString checksum = fileObj["checksum"].toString();
            
            newFileIds.insert(id);
            
            if (existingFileIds.contains(id)) {
                // 更新现有记录（不更新本地字段）
                updateQuery.bindValue(0, name);                  // NAME
                updateQuery.bindValue(1, diskId);                // DISK_ID
                updateQuery.bindValue(2, folderId);              // FOLDER_ID
                updateQuery.bindValue(3, creator);               // CREATOR
                updateQuery.bindValue(4, creatorId);             // CREATOR_ID
                updateQuery.bindValue(5, type);                  // TYPE
                updateQuery.bindValue(6, createDate);            // CREATE_DATE
                updateQuery.bindValue(7, lastModifyDate);        // LAST_MODIFY_DATE
                updateQuery.bindValue(8, originType);            // ORIGIN_TYPE
                updateQuery.bindValue(9, originId);             // ORIGIN_ID
                updateQuery.bindValue(10, size);                 // SIZE
                updateQuery.bindValue(11, removeOperator);       // REMOVE_OPERATOR
                updateQuery.bindValue(12, checksum);             // CHECKSUM
                updateQuery.bindValue(13, id);                   // WHERE ID
                
                if (!updateQuery.exec()) {
                    qDebug() << "更新文件记录失败:" << updateQuery.lastError().text();
                } else {
                    updateCount++;
                }
            } else {
                // 插入新记录（不设置本地字段，使用默认值）
                insertQuery.bindValue(0, id);                    // ID
                insertQuery.bindValue(1, name);                  // NAME
                insertQuery.bindValue(2, diskId);                // DISK_ID
                insertQuery.bindValue(3, folderId);              // FOLDER_ID
                insertQuery.bindValue(4, creator);               // CREATOR
                insertQuery.bindValue(5, creatorId);             // CREATOR_ID
                insertQuery.bindValue(6, type);                  // TYPE
                insertQuery.bindValue(7, createDate);            // CREATE_DATE
                insertQuery.bindValue(8, lastModifyDate);        // LAST_MODIFY_DATE
                insertQuery.bindValue(9, originType);           // ORIGIN_TYPE
                insertQuery.bindValue(10, originId);             // ORIGIN_ID
                insertQuery.bindValue(11, size);                 // SIZE
                insertQuery.bindValue(12, removeOperator);       // REMOVE_OPERATOR
                insertQuery.bindValue(13, checksum);             // CHECKSUM
                
                if (!insertQuery.exec()) {
                    qDebug() << "插入文件记录失败:" << insertQuery.lastError().text();
                } else {
                    insertCount++;
                }
            }
        }
        
        // 删除不在新数据中的文件（逻辑删除）
        for (const QString &existingId : existingFileIds) {
            if (!newFileIds.contains(existingId)) {
                QSqlQuery deleteQuery(m_database);
                deleteQuery.prepare("UPDATE kms_file SET STATUS = -1 WHERE ID = ?");
                deleteQuery.addBindValue(existingId);
                if (!deleteQuery.exec()) {
                    qDebug() << "标记删除文件失败:" << deleteQuery.lastError().text();
                }
            }
        }
        
        m_database.commit();
        qDebug() << "同步文件数据完成 - 插入:" << insertCount << "更新:" << updateCount;
        return true;
        
    } catch (const std::exception &e) {
        qDebug() << "同步文件数据时发生异常:" << e.what();
        m_database.rollback();
        return false;
    } catch (...) {
        qDebug() << "同步文件数据时发生异常";
        m_database.rollback();
        return false;
    }
}

bool DatabaseManager::updateLocalFileInfo(const QString &fileId, qint64 localFileSize, const QString &localFileChecksum, const QString &localFilePath)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接，无法更新本地文件信息";
        return false;
    }
    
    QSqlQuery query(m_database);
    if (!localFilePath.isEmpty()) {
        query.prepare("UPDATE kms_file SET LOCAL_FILE_SIZE = ?, LOCAL_FILE_CHECKSUM = ?, LOCAL_FILE_PATH = ? WHERE ID = ?");
        query.addBindValue(localFileSize);
        query.addBindValue(localFileChecksum);
        query.addBindValue(localFilePath);
        query.addBindValue(fileId);
    } else {
        query.prepare("UPDATE kms_file SET LOCAL_FILE_SIZE = ?, LOCAL_FILE_CHECKSUM = ? WHERE ID = ?");
        query.addBindValue(localFileSize);
        query.addBindValue(localFileChecksum);
        query.addBindValue(fileId);
    }
    
    if (query.exec()) {
        qDebug() << "成功更新本地文件信息，文件ID:" << fileId << "大小:" << localFileSize << "本地校验和:" << localFileChecksum << "本地路径:" << localFilePath;
        return true;
    } else {
        qDebug() << "更新本地文件信息失败:" << query.lastError().text();
        return false;
    }
}

bool DatabaseManager::clearLocalFileInfo(const QString &fileId)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接，无法清除本地文件信息";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("UPDATE kms_file SET LOCAL_FILE_SIZE = 0, LOCAL_FILE_CHECKSUM = NULL, LOCAL_FILE_PATH = NULL WHERE ID = ?");
    query.addBindValue(fileId);
    
    if (query.exec()) {
        qDebug() << "成功清除本地文件信息，文件ID:" << fileId;
        return true;
    } else {
        qDebug() << "清除本地文件信息失败:" << query.lastError().text();
        return false;
    }
}

bool DatabaseManager::updateFileStatus(const QString &fileId, int status)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接，无法更新文件状态";
        return false;
    }
    QSqlQuery query(m_database);
    query.prepare("UPDATE kms_file SET STATUS = ? WHERE ID = ?");
    query.addBindValue(status);
    query.addBindValue(fileId);
    if (!query.exec()) {
        qDebug() << "更新文件状态失败:" << query.lastError().text();
        return false;
    }
    qDebug() << "成功更新文件状态，文件ID:" << fileId << "状态:" << status;
    
    // 联动更新文件夹状态
    updateFolderStatusByFileChange(fileId);
    
    return true;
}


// 文件夹状态管理方法实现

QList<KmsFolder> DatabaseManager::querySubFoldersByFolderId(const QString &folderId)
{
    QList<KmsFolder> folders;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return folders;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_folder WHERE FOLDER_ID = ?");
    query.addBindValue(folderId);
    
    if (!query.exec()) {
        qDebug() << "查询子文件夹失败:" << query.lastError().text();
        return folders;
    }
    
    while (query.next()) {
        KmsFolder folder;
        folder.id = query.value("ID").toString();
        folder.name = query.value("NAME").toString();
        folder.diskId = query.value("DISK_ID").toString();
        folder.folderId = query.value("FOLDER_ID").toString();
        folder.path = query.value("PATH").toString();
        folder.creator = query.value("CREATOR").toString();
        folder.creatorId = query.value("CREATOR_ID").toString();
        folder.type = query.value("TYPE").toInt();
        folder.createDate = query.value("CREATE_DATE").toString();
        folder.lastModifyDate = query.value("LAST_MODIFY_DATE").toString();
        folder.orderNo = query.value("ORDER_NO").toInt();
        folder.removeOperator = query.value("REMOVE_OPERATOR").toString();
        folder.status = query.value("STATUS").toInt();
        folder.version = query.value("VERSION").toInt();
        folder.maxVersion = query.value("MAX_VERSION").toInt();
        folders.append(folder);
    }
    
    return folders;
}

QList<KmsFile> DatabaseManager::querySubFilesByFolderId(const QString &folderId)
{
    QList<KmsFile> files;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return files;
    }
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_file WHERE FOLDER_ID = ?");
    query.addBindValue(folderId);
    
    if (!query.exec()) {
        qDebug() << "查询子文件失败:" << query.lastError().text();
        return files;
    }
    
    while (query.next()) {
        KmsFile file;
        file.id = query.value("ID").toString();
        file.name = query.value("NAME").toString();
        file.diskId = query.value("DISK_ID").toString();
        file.folderId = query.value("FOLDER_ID").toString();
        file.creator = query.value("CREATOR").toString();
        file.creatorId = query.value("CREATOR_ID").toString();
        file.type = query.value("TYPE").toString();
        file.createDate = query.value("CREATE_DATE").toString();
        file.lastModifyDate = query.value("LAST_MODIFY_DATE").toString();
        file.originType = query.value("ORIGIN_TYPE").toInt();
        file.originId = query.value("ORIGIN_ID").toString();
        file.size = query.value("SIZE").toLongLong();
        file.removeOperator = query.value("REMOVE_OPERATOR").toString();
        file.status = query.value("STATUS").toInt();
        file.checksum = query.value("CHECKSUM").toString();
        file.localFileSize = query.value("LOCAL_FILE_SIZE").toLongLong();
        file.localFileChecksum = query.value("LOCAL_FILE_CHECKSUM").toString();
        file.localFilePath = query.value("LOCAL_FILE_PATH").toString();
        files.append(file);
    }
    
    return files;
}

int DatabaseManager::calculateFolderStatus(const QString &folderId)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接，无法计算文件夹状态";
        return 0;
    }
    
    // 获取子文件夹和子文件
    QList<KmsFolder> subFolders = querySubFoldersByFolderId(folderId);
    QList<KmsFile> subFiles = querySubFilesByFolderId(folderId);
    
    // 如果没有子元素，返回默认状态
    if (subFolders.isEmpty() && subFiles.isEmpty()) {
        qDebug() << "文件夹" << folderId << "没有子元素，返回默认状态0";
        return 0;
    }
    
    bool hasDeleted = false;  // 存在status = -1
    bool hasModified = false; // 存在status = 2
    bool allSynced = true;    // 所有元素都是status = 1
    
    // 检查子文件夹状态
    for (const KmsFolder &folder : subFolders) {
        if (folder.status == -1) {
            hasDeleted = true;
            allSynced = false;
        } else if (folder.status == 2) {
            hasModified = true;
            allSynced = false;
        } else if (folder.status != 1) {
            allSynced = false;
        }
    }
    
    // 检查子文件状态
    for (const KmsFile &file : subFiles) {
        if (file.status == -1) {
            hasDeleted = true;
            allSynced = false;
        } else if (file.status == 2) {
            hasModified = true;
            allSynced = false;
        } else if (file.status != 1) {
            allSynced = false;
        }
    }
    
    // 根据规则计算状态
    int calculatedStatus;
    if (hasDeleted) {
        calculatedStatus = 2; // 存在删除标记，文件夹状态为2
    } else if (hasModified) {
        calculatedStatus = 2; // 存在修改，文件夹状态为2
    } else if (allSynced) {
        calculatedStatus = 1; // 所有子元素都已同步，文件夹状态为1
    } else {
        calculatedStatus = 0; // 其他情况，文件夹状态为0
    }
    
    qDebug() << "计算文件夹" << folderId << "状态: 删除=" << hasDeleted 
             << " 修改=" << hasModified << " 全同步=" << allSynced 
             << " 计算结果=" << calculatedStatus;
    
    return calculatedStatus;
}

bool DatabaseManager::updateFolderStatusRecursively(const QString &folderId)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接，无法更新文件夹状态";
        return false;
    }
    
    if (folderId.isEmpty()) {
        qDebug() << "文件夹ID为空，无法更新状态";
        return false;
    }
    
    // 计算当前文件夹的新状态
    int newStatus = calculateFolderStatus(folderId);
    
    // 更新当前文件夹状态
    QSqlQuery query(m_database);
    query.prepare("UPDATE kms_folder SET STATUS = ? WHERE ID = ?");
    query.addBindValue(newStatus);
    query.addBindValue(folderId);
    
    if (!query.exec()) {
        qDebug() << "更新文件夹状态失败:" << query.lastError().text();
        return false;
    }
    
    qDebug() << "成功更新文件夹" << folderId << "状态为:" << newStatus;
    
    // 查找父文件夹并递归更新
    QSqlQuery parentQuery(m_database);
    parentQuery.prepare("SELECT FOLDER_ID FROM kms_folder WHERE ID = ?");
    parentQuery.addBindValue(folderId);
    
    if (parentQuery.exec() && parentQuery.next()) {
        QString parentFolderId = parentQuery.value("FOLDER_ID").toString();
        if (!parentFolderId.isEmpty()) {
            qDebug() << "递归更新父文件夹" << parentFolderId << "状态";
            return updateFolderStatusRecursively(parentFolderId);
        }
    }
    
    return true;
}

bool DatabaseManager::updateFolderStatusByFileChange(const QString &fileId)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接，无法根据文件变更更新文件夹状态";
        return false;
    }
    
    if (fileId.isEmpty()) {
        qDebug() << "文件ID为空，无法更新文件夹状态";
        return false;
    }
    
    // 查找文件所属的文件夹ID
    QSqlQuery query(m_database);
    query.prepare("SELECT FOLDER_ID FROM kms_file WHERE ID = ?");
    query.addBindValue(fileId);
    
    if (!query.exec() || !query.next()) {
        qDebug() << "查找文件所属文件夹失败:" << query.lastError().text();
        return false;
    }
    
    QString folderId = query.value("FOLDER_ID").toString();
    if (folderId.isEmpty()) {
        qDebug() << "文件" << fileId << "没有所属文件夹，跳过文件夹状态更新";
        return true;
    }
    
    qDebug() << "文件" << fileId << "变更，开始更新文件夹" << folderId << "状态";
    
    // 递归更新文件夹状态
    return updateFolderStatusRecursively(folderId);
}

bool DatabaseManager::updateFolderStatus(const QString &folderId)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接，无法更新文件夹状态";
        return false;
    }
    
    if (folderId.isEmpty()) {
        qDebug() << "文件夹ID为空，无法更新状态";
        return false;
    }
    
    qDebug() << "手动更新文件夹" << folderId << "状态";
    
    // 递归更新文件夹状态
    return updateFolderStatusRecursively(folderId);
}

// 命令记录操作
bool DatabaseManager::insertCommand(const KmsCommand &command)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("INSERT INTO kms_command (ID, CREATE_DATE, LOCAL_FILE_PATH, DOWNLOAD_URL, COMMIT_URL, ACCESS_TOKEN, COMMAND) "
                  "VALUES (?, ?, ?, ?, ?, ?, ?)");
    
    query.addBindValue(command.id);
    query.addBindValue(command.createDate);
    query.addBindValue(command.localFilePath);
    query.addBindValue(command.downloadUrl);
    query.addBindValue(command.commitUrl);
    query.addBindValue(command.accessToken);
    query.addBindValue(command.command);
    
    if (!query.exec()) {
        qDebug() << "插入命令记录失败:" << query.lastError().text();
        return false;
    }
    
    qDebug() << "成功插入命令记录，ID:" << command.id << "命令:" << command.command;
    return true;
}

bool DatabaseManager::updateCommandLocalFilePath(const QString &downloadUrl, const QString &localFilePath)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    if (downloadUrl.isEmpty()) {
        qDebug() << "下载URL为空，无法更新命令记录";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("UPDATE kms_command SET LOCAL_FILE_PATH = ? WHERE DOWNLOAD_URL = ?");
    
    query.addBindValue(localFilePath);
    query.addBindValue(downloadUrl);
    
    if (!query.exec()) {
        qDebug() << "更新命令记录LOCAL_FILE_PATH失败:" << query.lastError().text();
        return false;
    }
    
    if (query.numRowsAffected() > 0) {
        qDebug() << "成功更新命令记录LOCAL_FILE_PATH，下载URL:" << downloadUrl << "本地路径:" << localFilePath;
        return true;
    } else {
        qDebug() << "未找到匹配的命令记录，下载URL:" << downloadUrl;
        return false;
    }
}

KmsCommand DatabaseManager::queryCommandByLocalFilePath(const QString &localFilePath)
{
    KmsCommand command;
    
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return command;
    }
    
    if (localFilePath.isEmpty()) {
        qDebug() << "本地文件路径为空，无法查询命令记录";
        return command;
    }
    
    // 使用尾部匹配查询 LOCAL_FILE_PATH
    // SQLite 使用 LIKE 操作符，% 表示任意字符
    // 注意：需要统一路径分隔符，确保匹配正确
    QString normalizedPath = QDir::cleanPath(localFilePath);
    // 将路径分隔符统一为正斜杠，以便跨平台匹配
    normalizedPath = normalizedPath.replace('\\', '/');
    
    QSqlQuery query(m_database);
    query.prepare("SELECT * FROM kms_command WHERE LOCAL_FILE_PATH LIKE ?");
    query.addBindValue("%" + normalizedPath);
    
    if (!query.exec()) {
        qDebug() << "查询命令记录失败:" << query.lastError().text();
        return command;
    }
    
    if (query.next()) {
        command.id = query.value("ID").toString();
        command.createDate = query.value("CREATE_DATE").toString();
        command.localFilePath = query.value("LOCAL_FILE_PATH").toString();
        command.downloadUrl = query.value("DOWNLOAD_URL").toString();
        command.commitUrl = query.value("COMMIT_URL").toString();
        command.accessToken = query.value("ACCESS_TOKEN").toString();
        command.command = query.value("COMMAND").toString();
        
        qDebug() << "找到匹配的命令记录，ID:" << command.id << "本地路径:" << command.localFilePath;
    } else {
        qDebug() << "未找到匹配的命令记录，本地路径:" << localFilePath;
    }
    
    return command;
}

bool DatabaseManager::deleteCommandByCommitUrl(const QString &commitUrl)
{
    if (!isDatabaseConnected()) {
        qDebug() << "数据库未连接";
        return false;
    }
    
    if (commitUrl.isEmpty()) {
        qDebug() << "提交URL为空，无法删除命令记录";
        return false;
    }
    
    QSqlQuery query(m_database);
    query.prepare("DELETE FROM kms_command WHERE COMMIT_URL = ?");
    query.addBindValue(commitUrl);
    
    if (!query.exec()) {
        qDebug() << "删除命令记录失败:" << query.lastError().text();
        return false;
    }
    
    if (query.numRowsAffected() > 0) {
        qDebug() << "成功删除命令记录，提交URL:" << commitUrl;
        return true;
    } else {
        qDebug() << "未找到匹配的命令记录，提交URL:" << commitUrl;
        return false;
    }
}